package com.poseidon;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * java事务控制
 * 
 * @author JingChenglong 2018/01/07 20:08
 *
 */
public class TransactionLearn {

	public static void main(String[] args) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pandora", "root", "root");
		Statement statement = conn.createStatement();
		String sql1 = "update staff set num = num - 10 where id = 1 ";
		String sql2 = "update staff set num = num + 10 where id = 21 ";
		try {
			conn.setAutoCommit(false);
			if (1 != statement.executeUpdate(sql1)) {
				throw new Exception("减操作失败");
			}
			if (1 != statement.executeUpdate(sql2)) {
				throw new Exception("加操作失败");
			}
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
		}
	}
}